package com.itheima.controller;


import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.core.metadata.OrderItem;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.itheima.pojo.*;
import com.itheima.service.ClazzService;
import com.itheima.service.StudentService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.util.CollectionUtils;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.*;

import java.time.LocalDateTime;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

@Slf4j
@RestController
@RequestMapping("/students")
public class StudentController {

    @Autowired
    private StudentService studentService;
    @Autowired
    private ClazzService clazzService;

    @GetMapping
    public Result list(StudentQueryParam student) {
        log.info("查询所有学生信息：{}", student);
        //分页查询
        //全部结果
        IPage<Student> page = Page.of(student.getPage(), student.getPageSize());
        //添加排序规则-修改时间倒序
        //service查询数据
        //去除硬编码还可以使用wrapper.desc
        LambdaQueryWrapper<Student> wrapper = new LambdaQueryWrapper<>();
        wrapper.like(StringUtils.hasLength(student.getName()), Student::getName, student.getName())
                .eq(student.getDegree() != null, Student::getDegree, student.getDegree())
                .eq(student.getClazzId() != null, Student::getClazzId, student.getClazzId())
                .orderByDesc(Student::getUpdateTime);
        page = studentService.page(page, wrapper);
        //把班级名称赋值过去
        List<Student> students = page.getRecords();
        if(!CollectionUtils.isEmpty(students)) {
            List<Integer> stuClazzId = students.stream().map(Student::getClazzId).distinct().toList();
            List<Clazz> clazzes = clazzService.listByIds(stuClazzId);
            Map<Integer, String> clazzNames = clazzes.stream().collect(Collectors.toMap(Clazz::getId, Clazz::getName));
            students.forEach(stu-> stu.setClazzName(clazzNames.get(stu.getClazzId())));
        }
        return Result.success(new PageResult<>(page.getTotal(), page.getRecords()));
    }

    @PostMapping
    public Result save(@RequestBody Student student) {
        log.info("新增学生信息：{}", student);
        student.setUpdateTime(LocalDateTime.now());
        student.setCreateTime(LocalDateTime.now());
        studentService.save(student);
        return Result.success();
    }

    @GetMapping("/{id}")
    public Result getById(@PathVariable Integer id) {
        log.info("根据id查询学生信息：{}", id);
        Student studnet = studentService.getById(id);
        return Result.success(studnet);
    }

    @PutMapping
    public Result update(@RequestBody Student student) {
        log.info("修改学生信息：{}", student);
        student.setUpdateTime(LocalDateTime.now());
        studentService.updateById(student);
        return Result.success();
    }

    @DeleteMapping("/{ids}")
    public Result delete(@PathVariable List<Integer> ids) {
        log.info("根据id删除学生信息：{}", ids);
        studentService.removeByIds(ids);
        return Result.success();
    }

    @PutMapping("/violation/{id}/{score}")
    public Result violation(@PathVariable Integer id, @PathVariable Integer score) {
        log.info("根据id{}扣分, 扣分：{}", id, score);
        Student student = studentService.getById(id);
        student.setViolationCount((short) (student.getViolationCount() + 1));
        student.setViolationScore((short) (student.getViolationScore() + score));
        studentService.updateById(student);
        return Result.success();
    }
}
